#include "analog.h"
#include "main.h"

void analogInit(void)
{
    uint8_t TimeDelta = LL_ADC_DELAY_CALIB_ENABLE_ADC_CYCLES;

    LL_ADC_StartCalibration(ADC1);
    while (LL_ADC_IsCalibrationOnGoing(ADC1) != 0)
    {
    }
    LL_ADC_SetCalibrationFactor(ADC1, LL_ADC_GetCalibrationFactor(ADC1)); // 将校准向量写  ADC1中
    while (TimeDelta > 0)                                                 // 校准后延时
    {
        TimeDelta--;
    }
    LL_ADC_Enable(ADC1);
    while (LL_ADC_IsActiveFlag_ADRDY(ADC1) == 0)
    {
    }
}

uint16_t analogGetValue(uint8_t channel, uint16_t times)
{

    uint8_t ii = 0;
    unsigned long sum = 0;
    uint16_t average = 0;

    switch (channel)
    {
    case ANALOG_DP:
        LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_7);                // 设置通道1转换次序为1
        LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_7, LL_ADC_SAMPLINGTIME_160CYCLES_5); // 160.5个ADC周期
        break;
    case ANALOG_DN:
        LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_10);                // 设置通道1转换次序为1
        LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_10, LL_ADC_SAMPLINGTIME_160CYCLES_5); // 160.5个ADC周期
        break;
    case ANALOG_VCC:
        LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_1);                // 设置通道1转换次序为1
        LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_1, LL_ADC_SAMPLINGTIME_160CYCLES_5); // 160.5个ADC周期
        break;
    case ANALOG_NTC:
        LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_0);                // 设置通道1转换次序为
        LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_0, LL_ADC_SAMPLINGTIME_160CYCLES_5); // 160.5个ADC周期1
        break;
    default:
        return 0;
    }

    for (ii = 0; ii < times; ii++)
    {
        LL_ADC_REG_StartConversion(ADC1); // 用软件触发ADC转换
        while (LL_ADC_REG_IsConversionOngoing(ADC1))
            ; // 等待ADC转换完成
        sum += LL_ADC_REG_ReadConversionData12(ADC1);
        LL_ADC_REG_StopConversion(ADC1);
    }
    average = (uint16_t)(sum / times);
    return average;
}
